<template>
    <div class="content">

        <!--头部-->
        <div class="header-setting">
            <a-breadcrumb class="breadcrumb">
                <a-breadcrumb-item>
                    <a href="../mian">首页</a>
                </a-breadcrumb-item>
                <a-breadcrumb-item>设备管理</a-breadcrumb-item>
                <a-breadcrumb-item>设备版本管理</a-breadcrumb-item>
            </a-breadcrumb>

            <!--查询条件-->
            <div class="box-condition-body">
                <div class="box-condition-item">
                    <template>
                        <div style="margin: 0 0 0 50px">设备号</div>
                        <a-input
                                style="margin: 0 0 0 50px;width: 200px"
                                v-model="queryInputEquipmentNo"
                                @change="selectDeviceNo" placeholder="PX-001"/>
                    </template>
                    <template>
                        <div style="margin:0 0 0 50px">设备型号</div>
                        <a-select
                                style="margin: 0 100px 0 50px; width: 200px"
                                showSearch
                                placeholder="所有型号"
                                optionFilterProp="children"
                                @change="selectEquipmentModel"
                                :allowClear="allowClear"
                                v-model="queryEquipmentModelAttr"
                        >
                            <a-select-option v-for="e in equipmentModels" :key="e.id" :value="e.id">
                                {{e.modelCode}}
                            </a-select-option>
                        </a-select>
                    </template>
                    <!-- 停车点 -->
                    <template>
                        <div>停车点</div>
                        <a-select
                                style="margin: 0 0 0 50px; width: 200px"
                                showSearch
                                placeholder="选择停车点"
                                optionFilterProp="children"
                                @change="selectPark"
                                :allowClear="allowClear"
                                v-model="queryParkAttr"
                        >
                            <a-select-option v-for="p in parks" :key="p.id" :value="p.id">{{p.parkName}}
                            </a-select-option>
                        </a-select>
                    </template>
                </div>
                <div class="box-condition-item">
                    <template>
                        <div style="margin-left: 50px;">版本号</div>
                        <a-input
                                style="margin: 0 50px 0 50px;width: 200px" @ v-model="queryInputVersionStr"
                                @change="selectVersion" placeholder="0.0.0.1"/>
                    </template>
                    <!-- 设备支持最新版本号 -->
                    <template>
                        <div>设备支持最新得版本号</div>
                        <a-input
                                style="margin: 0 0 0 50px;width: 200px" v-model="newVersionDevice"
                                @change="selectLastVersion" placeholder="0.0.0.1"/>
                    </template>

                    <!-- <a-button style="margin: 0 0 0 20px" @click="queryData">查询</a-button> -->
                    <a-button style="margin: 0 0 0 20px" @click="resetQueryCondition">重置</a-button>
                </div>
            </div>
        </div>

        <!-- 表格内容 -->
        <div class="box-form">
            <!--工具栏-->
            <div class="box-tool">
                <div></div>
                <div style="display: flex">
                    <a-button @click="addClick" icon="plus">添加</a-button>
                    <a-button @click="editClick" icon="edit">编辑</a-button>
                    <a-button @click="editClickBatch" icon="edit">批量修改</a-button>
                    <template v-if="selectedRowKeys.length == 1">
                        <a-popconfirm title="确认删除？" okText="确认" cancelText="取消"
                                      @confirm="deleteClick">
                            <a-button icon="delete">删除</a-button>
                        </a-popconfirm>
                    </template>
                    <template v-else>
                        <a-button icon="delete" @click="deleteClick">删除</a-button>
                    </template>
                </div>
            </div>

            <!--数据表格-->
            <div class="box-table">
                <a-table
                        rowKey="no"
                        :columns="columns"
                        :dataSource="dataSource"
                        :pagination="pagination"
                        bordered size="small"
                        :scroll="scroll"
                        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
                        @change="tableChange">
                    <template slot="parkNameSlot" slot-scope="text">
                        <template v-if="text==undefined||text==''">
                            <div>待部署</div>
                        </template>
                        <template v-else>
                            <div>{{text}}</div>
                        </template>
                    </template>
                </a-table>
            </div>
        </div>

        <!-- 弹窗 -->
        <a-modal title="批量修改"
                 :confirmLoading="editPopupData.loading" :visible="editPopupData.visible"
                 @cancel="() => this.hideEditPopup()" @ok="commitEditPopup">
            <div class="box-popup-item">
                <div class="text-key">支持版本号</div>
                <div class="text-value">{{ this.editPopupData.selectVersion.version || '点击下方选择版本号'}}</div>
            </div>
            <!-- 版本列表 -->
            <div class="box-popup-content">
                <div style="display: flex;">
                    <div class="box-popup-item">
                        <div class="text-key">设备型号</div>
                        <a-select
                                style="width: 200px;"
                                showSearch
                                placeholder="所有型号"
                                :allowClear="allowClear"
                                @change="selectPopupDevice"
                                v-model="editPopupData.device">
                            <a-select-option v-for="e in equipmentModels" :key="e.id" :value="e.id">
                                {{e.modelCode}}
                            </a-select-option>
                        </a-select>
                    </div>
                    <div class="box-popup-item" style="margin-left: 50px;">
                        <div class="text-key">版本过滤</div>
                        <a-input placeholder="0.0.0.1" style="width: 200px;" v-model="editPopupData.version"
                                 @change="versionChange"/>
                    </div>
                </div>
                <!-- 上传日期 -->
                <div class="box-popup-item" style="margin-top: 20px;">
                    <div class="text-key">上传日期</div>
                    <a-range-picker
                            @change="dateChange"
                            v-model="editPopupData.momentArray"
                            format="YYYY-MM-DD"
                            :placeholder="['开始时间', '结束时间']"/>
                </div>
                <!-- 选项 -->
                <a-table
                        rowKey="id"
                        class="box-table"
                        :scroll="{y: 350}"
                        :customRow="(record) => {
                        return {
                            on: {
                                click: () => {
                                    this.editPopupData.selectVersion = record;
                                },
                            }
                        }
                    }"
                        @ok="commitEditPopup"
                        :columns="editPopupData.columns"
                        :dataSource="editPopupData.dataSource"
                        :pagination="editPopupData.pagination"
                        bordered size="small"
                        @change="popupTableChange"/>
            </div>
        </a-modal>

    </div>


</template>

<script>
    import EquipmentVersionManageApi from '../../api/equipment/EquipmentVersionManage';
    import CommonApi from "../../api/CommonApi";
    import EquipmentModelManageApi from '../../api/equipment/EquipmentModelManage';
    import AddPagesUtils from "../../utils/AddPagesUtils";
    import Constant from '../../utils/Constant';
    import UpdateServiceApi from "../../api/equipment/UpdateService";

    const columns = [
        {
            title: "设备号",
            dataIndex: "deviceSerialNumber",
            width: '20%'
        },
        {
            title: "设备型号",
            dataIndex: "modelCode",
            width: '10%'
        },
        {
            title: "停车点",
            dataIndex: "parkName",
            scopedSlots: {customRender: 'parkNameSlot'},
            width: '10%'
        },
        {
            title: "设备当前版本",
            dataIndex: "versionCurrent",
            width: '14%'
        },
        {
            title: "设备支持最新的版本",
            dataIndex: "versionLast",
            width: '14%'
        },
        {
            title: "创建人",
            dataIndex: "createUserName",
            width: '10%'
        },
        {
            title: "创建时间",
            dataIndex: "createdTime",
            width: '15%'
        },
    ];
    const dataSource = [];

    const queryCondition = {
        limit: "100",
        curr: "1",
        imei: "",
        deviceTypeId: "",
        version: "",
        parkId: "",
    };

    const editCondition = {
        id: "",
        version: "",
        downloadUri: "",
        deviceTypeId: "",
        updateContent: "",
        forbidUpdateStart: "",
        forbidUpdateEnd: "",
        softwareType: "0",
        onlineUpgradeSwitch: 0,
    };

    export default {
        name: "EquipmentVersionManage",
        /*数据层*/
        data() {
            return {
                /**常量**/
                queryCondition,
                editCondition,
                /**查询条件字段**/
                queryInputEquipmentNo: "",
                queryInputVersionStr: "",
                queryEquipmentModelAttr: [],
                queryParkAttr: [],
                newVersionDevice: "",
                /**表格**/
                columns: columns,
                dataSource: dataSource,
                /*分页插件*/
                pagination: {
                    showTotal: total => `共${total}条`,
                    total: 0,
                    current: 1,
                    defaultCurrent: 1,
                    showQuickJumper: true,
                    defaultPageSize: 100
                },
                /* 选择 */
                selectedRowKeys: [],

                /*表格固定头部*/
                scroll: {
                    y: 550,
                },
                /*当前选中的行数据*/
                /**设备型号下拉框**/
                allowClear: true,
                equipmentModels: [],
                /**停车点下拉框**/
                parks: [],


                /* -------------- 弹窗 -------------- */
                editPopupData: {
                    /* 常量 */
                    pagination: {
                        showTotal: total => `共${total}条`,
                        total: 0,
                        current: 1,
                        defaultCurrent: 1,
                        showQuickJumper: true,
                        defaultPageSize: 10
                    },
                    dataSource: [],
                    columns: [
                        {
                            title: "版本号",
                            dataIndex: "version",
                            width: '10%'
                        },
                        {
                            title: "更新内容",
                            dataIndex: "updateContent",
                            width: '25%'
                        },
                        {
                            title: "下载地址",
                            dataIndex: "downloadUri",
                            width: '20%'
                        },
                        {
                            title: "上传者",
                            dataIndex: "nickName",
                            width: '20%'
                        },
                        {
                            title: "上传时间",
                            dataIndex: "createdTime",
                            // width: '20%'
                        }
                    ],
                    /* 可变量 */
                    visible: false,
                    momentArray: [],
                    version: "",
                    selectVersion: "",
                    device: "",
                    loading: false,
                }
            }
        },
        /*方法层*/
        methods: {
            initData() {
                this.initEquipmentModels();
                this.initParks();
                this.queryData();
            },

            /* ------------------- 设备型号 ------------------- */
            initEquipmentModels() {
                EquipmentModelManageApi.getDeviceTypeList()
                    .then((data) => {
                        this.equipmentModels = data.data;
                    })
                    .catch(err => {
                        console.log("获取设备型号数据异常！", err);
                    });
            },

            /* ------------------- 停车列表 ------------------- */
            initParks() {
                CommonApi.getParkList()
                    .then((data,) => {
                        let nodelopy={id:0,parkName:'待部署'}
                        this.parks = data.data;
                        this.parks.unshift(nodelopy);
                    })
                    .catch(err => {
                        console.log("error:", err);
                    });
            },

            /* ------------------- 条件 ------------------- */
            selectDeviceNo() {
                this.queryData();
            },

            selectEquipmentModel() {
                this.queryData();
            },

            selectPark() {
                this.queryData();
            },

            resetQueryCondition() {
                this.queryInputEquipmentNo = "";
                this.queryEquipmentModelAttr = [];
                this.queryParkAttr = [];
                this.queryInputVersionStr = "";
                this.newVersionDevice = "";
                this.queryData();
            },

            selectVersion() {
                this.queryData();
            },

            selectLastVersion() {
                this.queryData();
            },

            /* ------------------- 设备版本列表 ------------------- */
            queryData(pageNum) {
                this.clearSelectArray();
                /* condition */
                let queryParkAttr = this.queryParkAttr;
                if (queryParkAttr === 0) {
                    queryParkAttr = '0';
                }
                let condition = this.queryCondition;
                condition.curr = pageNum || 1;
                condition.imei = this.queryInputEquipmentNo || "";
                condition.deviceTypeId = this.queryEquipmentModelAttr || "";
                condition.parkId =  queryParkAttr || "";
                condition.version = this.queryInputVersionStr || "";
                condition.versionLast = this.newVersionDevice || "";

                /* api */
                EquipmentVersionManageApi.getDeviceVersionRecordList(condition)
                    .then((data) => {
                        let {list, total, pageNum, pageSize} = data.data;

                        let array = list || [];
                        array = array.map((item, index) => {
                            return {...item, no: total - (pageNum - 1) * pageSize - index};
                        })
                        this.dataSource = array;
                        this.pagination.total = total;
                        this.pagination.current = pageNum;
                    })
                    .catch(err => {
                        console.log("获取设备版本信息列表异常！", err);
                    })
            },

            /* ------------------- 表单事件 ------------------- */
            tableChange(page) {
                this.queryData(page.current);
            },


            /* --------------------- 事件 --------------------- */
            addClick() {
                AddPagesUtils.showAddPages(Constant.viewType.EQUIPMENT_VERSION_ADD, null, this.callBackFunc);
            },
            editClick() {
                let selectArray = this.getSelectArray(), len = selectArray.length;
                if (len == 0) {
                    this.$message.error("请选择数据");
                    return;
                }
                if (len > 1) {
                    this.$message.error("只能选择一个");
                    return;
                }
                //传递数据
                let data = selectArray[0];
                if (data == undefined || data == '') {
                    return this.$message.warn("请选择编辑的数据！");
                }
                AddPagesUtils.showAddPages(Constant.viewType.EQUIPMENT_VERSION_EDIT, data, this.callBackFunc);
            },
            editClickBatch() {
                let selectArray = this.getSelectArray(), len = selectArray.length;
                if (len == 0) {
                    this.$message.error("请至少选择一个")
                    return;
                }
                this.showEditPopup(selectArray);
            },

            callBackFunc(data) {
                let sign = data.operateSign;
                if (sign == 1) {
                    EquipmentVersionManageApi.addDeviceVersionRecord(data)
                        .then(() => {
                            this.$message.success("添加成功！");
                            this.queryData();
                        })
                        .catch(err => {
                            let data = err.data;
                            if (data) {
                                return this.$message.warn(data);
                            }
                        });
                } else if (sign == 2) {
                    EquipmentVersionManageApi.updateDeviceVersionRecord(data)
                        .then(() => {
                            this.$message.success("修改成功！");
                            this.queryData();
                        })
                        .catch(err => {
                            let data = err.data;
                            if (data) {
                                return this.$message.warn(data);
                            }
                        });
                } else {
                    console.error("非法操作信号", data);
                }

            },

            deleteClick() {
                let selectArray = this.getSelectArray(), len = selectArray.length;
                if (len == 0) {
                    this.$message.error("请选择一个删除项")
                    return;
                }

                if (len != 1) {
                    this.$message.error("只能选择一个删除");
                    return;
                }

                let {id} = selectArray[0]
                EquipmentVersionManageApi.deleteDeviceVersionRecord({id})
                    .then(() => {
                        this.$message.success("删除成功！");
                        this.queryData();
                    })
                    .catch( err=> {
                        this.$message.error("设备版本信息删除异常！"+err);
                    });
            },

            /* --------------------- selectArray --------------------- */
            getSelectArray() {
                let dataSource = this.dataSource || [];
                let selectedRowKeys = this.selectedRowKeys;
                return dataSource.filter(item => {
                    return selectedRowKeys.filter(no => no == item.no).length > 0;
                })
            },

            clearSelectArray() {
                this.selectedRowKeys = [];
            },

            onSelectChange(selectedRowKeys) {
                this.selectedRowKeys = selectedRowKeys;
            },

            /* -------------------- 弹窗 ------------------------- */
            showEditPopup(array) {
                this.editPopupData.visible = true;
                this.editPopupData.loading = false;
                this.editPopupData.ids = array.map(item => item.id).join(',');
                this.editPopupData.momentArray = [];
                this.editPopupData.version = [];
                this.queryPopupData();
            },

            hideEditPopup() {
                this.editPopupData.visible = false;
            },

            versionChange() {
                this.queryPopupData();
            },

            dateChange() {
                this.queryPopupData();
            },

            queryPopupData() {
                let momentArray = this.editPopupData.momentArray;
                let st = '', et = '';
                if (momentArray.length == 2) {
                    st = this.editPopupData.momentArray[0].format('YYYY-MM-DD')
                    et = this.editPopupData.momentArray[1].format('YYYY-MM-DD');
                }
                let deviceTypeId = this.editPopupData.device || "";
                let condition = {
                    version: this.editPopupData.version || '',
                    uploadTimeStart: st, uploadTimeEnd: et,
                    softwareType: 0, deviceTypeId
                }
                UpdateServiceApi.getVersionManageList(condition)
                    .then((data) => {
                        let {total, list, pageNum} = data.data;

                        this.editPopupData.dataSource = list;
                        this.editPopupData.pagination.total = total;
                        this.editPopupData.pagination.pageNum = pageNum;
                    })
                    .catch(err => {
                        this.$message.error("获取设备版本信息异常:"+err);
                    });
            },

            popupTableChange(page) {
                this.queryPopupData(page.current);
            },

            selectPopupDevice() {
                this.queryPopupData();
            },

            commitEditPopup() {
                let item = this.editPopupData.selectVersion
                if (!item || !item.version) {
                    this.$message.error("请先选择一个版本");
                    return;
                }
                let version = item.version;
                let ids = this.editPopupData.ids;
                this.editPopupData.loading = true;
                UpdateServiceApi.batchUpdateDeviceVersion({ids, updateVersion: version})
                    .then(() => {
                        this.$message.info("更新成功");
                        this.editPopupData.loading = false;
                        this.hideEditPopup();

                        this.queryData();
                    })
                    .catch(() => {
                        this.$message.error("更新失败");
                        this.editPopupData.loading = false;
                    })
            },
        },

        /*计算层*/
        computed: {},

        mounted() {
            this.initData();
        },
    }
</script>

<style scoped>
    .content {
        width: 100%;
        height: 100%;
    }

    .header-setting {
        width: 100%;
        height: 174px;
        background: #fff;
    }

    .header-setting .breadcrumb {
        margin-left: 41px;
        padding-top: 15px;
    }

    /*表格行选中背景颜色*/
    .clickRowStyl {
        background-color: #C1E0FD;
    }

    .box-condition-item {
        display: flex;
        align-items: center;
        min-width: 1500px;
        margin-top: 10px;
        margin-bottom: 10px;
        padding: 5px 0;
    }

    box-condition-body {
        margin: 0 0 0 100px;
    }

    /* 表单 */
    .box-form {
        padding-left: 40px;
        padding-right: 40px;
        min-height: 705px;
        background: #fff;
        margin-top: 8px;
    }

    .box-form .box-tool {
        padding-top: 11px;
        margin: 8px 0;
        width: 100%;
        /* flex */
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .box-tool button {
        margin-right: 10px;
    }

    .ant-switch-checked {
        background-color: #1890ff;
    }

    /* 弹窗 */
    .box-popup-item {
        width: 100%;
        display: flex;
        align-items: center;
    }

    .box-popup-item .text-key {
        width: 100px;
        flex: 0 1 auto;
    }

    .box-popup-item .text-value {
        padding: 0 10px;
        width: 200px;
        height: 30px;
        font-size: 14px;
        border: 1px solid #d9d9d9;
        border-radius: 4px;
        line-height: 30px;
        cursor: pointer;
    }

    .box-popup-content {
        width: 100%;
        margin-top: 30px;
        padding: 20px;
        background: #F0F0F0;
    }

    .box-popup-content .box-table {
        margin-top: 30px;
    }


</style>
